using System;
using CommunityServer.Controls;
using CommunityServer.Components;
using System.Web.UI.WebControls;
using System.Collections.Generic;

namespace CommunityServerStuff.Controls
{
    public class RolePickerSubForm : WrappedSubFormBase
    {

        #region Private Members

        // storage for the reference to the DropDownList containing car brands
        ListControl RolesList;
        private List<string> _excludedRoles = null;
        private string administrators = "SystemAdministrator,MembershipAdministrator,ForumsAdministrator,BlogAdministrator,ForumAdminstrator,ReaderAdministrator,FileAdministrator,GalleryAdministrator";
        private string systemRoles = "Moderator,Editor,Everyone,Owners,ReaderUser,Registered Users,Trusted Users";
        private char[] splitter = { ',' };

        #endregion

        #region Properties

        #region ExcludedRoles

        /// <summary>
        /// A comma-delimited list of roles to exclude.
        /// </summary>
        public string ExcludedRoles
        {
            get { return (string)(ViewState["ExcludedRoles"] ?? ""); }
            set
            {
                ViewState["ExcludedRoles"] = value;
                if (!string.IsNullOrEmpty(value))
                {
                    if (_excludedRoles == null)
                        _excludedRoles = new List<string>();
                     _excludedRoles.AddRange(value.Split(splitter, System.StringSplitOptions.RemoveEmptyEntries));
                }
            }
        }

        #endregion

        #region ExcludeAdministrativeRoles

        /// <summary>
        /// Automatically removes the built-in administrative roles (SystemAdministrator, etc).
        /// </summary>
        public bool ExcludeAdministrativeRoles
        {
            get { return (bool)(ViewState["ExcludeAdministrativeRoles"] ?? false); }
            set
            {
                ViewState["ExcludeAdministrativeRoles"] = value;
                if (value)
                {
                    if (_excludedRoles == null)
                        _excludedRoles = new List<string>();
                    _excludedRoles.AddRange(administrators.Split(splitter, System.StringSplitOptions.RemoveEmptyEntries));
                }
            }
        }

        #endregion

        #region ExcludeBuiltInRoles

        /// <summary>
        /// Automatically removes all of the built-in system roles (SystemAdministrator, Owners, Registered Users, etc).
        /// </summary>
        public bool ExcludeBuiltInRoles
        {
            get { return (bool)(ViewState["ExcludeBuiltInRoles"] ?? false); }
            set
            {
                ViewState["ExcludeBuiltInRoles"] = value;
                if (value)
                {
                    if (_excludedRoles == null)
                        _excludedRoles = new List<string>();
                    _excludedRoles.AddRange(administrators.Split(splitter, System.StringSplitOptions.RemoveEmptyEntries));
                    _excludedRoles.AddRange(systemRoles.Split(splitter, System.StringSplitOptions.RemoveEmptyEntries));
                }
            }
        }

        #endregion

        #region ExcludeNonAdministrativeRoles

        /// <summary>
        /// Automatically removes all of the built-in system roles (Owners, Registered Users, etc).
        /// </summary>
        public bool ExcludeNonAdministrativeRoles
        {
            get { return (bool)(ViewState["ExcludeNonAdministrativeRoles"] ?? false); }
            set
            {
                ViewState["ExcludeNonAdministrativeRoles"] = value;
                if (value)
                {
                    if (_excludedRoles == null)
                        _excludedRoles = new List<string>();
                    _excludedRoles.AddRange(systemRoles.Split(splitter, System.StringSplitOptions.RemoveEmptyEntries));
                }
            }
        }

        #endregion

        #region RolesListId

        /// <summary>
        ///  this property will be used to allow the theme developer to provide the ID of the DropDownList containing site roles
        /// </summary>
        public string RolesListId
        {
            get { return (string)(ViewState["RoleListId"] ?? ""); }
            set { ViewState["RoleListId"] = value; }
        }

        #endregion

        #region IsEnabled

        public override bool IsEnabled()
        {
            // permissions can also be checked here.
            return true;
        }

        #endregion

        #endregion

        #region Methods

        #region AttachChildControls

        protected override void AttachChildControls()
        {
            // find the DropDownList that will contain roles
            this.RolesList = CSControlUtility.Instance().FindControl(this, this.RolesListId) as ListControl;

            // if the DropDownList couldn't be found, throw an exception
            if (this.RolesList == null)
                throw new InvalidOperationException("The RolesListId must identify a valid DropDownList to render a RolePickerSubForm"); 

            // retrieve the current selected value
            string selectedValue = this.RolesList.SelectedValue;

            // clear and (re)populate the DropDownList
            this.RolesList.Items.Clear();
            string[] roles = Roles.GetRoleNames();

            for (int i = 0; i <= roles.Length - 1; i++)
            {
                if (!_excludedRoles.Contains(roles[i]))
                    this.RolesList.Items.Add(new ListItem(roles[i], roles[i]));
            }

            //foreach(string role in _excludedRoles)
            //{
            //    int index = Array.IndexOf(roles, role);
            //    if (index == -1)
                    
            //}
 
            // attempt to re-set the selected value
            if (this.RolesList.Items.FindByValue(selectedValue) != null)
                this.RolesList.SelectedValue = selectedValue;
        }

        #endregion

        #endregion

        #region DataBind

        public override void DataBind()
        {
            // call the base DataBind method -- it enabled DisplayConditions and other Chameleon features
            base.DataBind();

            // the DataSource is automatically set to the host form's DataSource
            // if it is a User object, load the user's existing brand selection
            User user = this.DataSource as User;
            if (user != null && !this.Page.IsPostBack)
            {
                string[] roles = Roles.GetUserRoleNames(user.Username);
                for (int i = 0; i <= roles.Length - 1; i++)
                {
                    if (this.RolesList.Items.FindByValue(roles[i]) != null)
                        this.RolesList.SelectedValue = roles[i];
                }

            }
        }

        #endregion

        #region ApplyChangesBeforeCommit

        public override void ApplyChangesBeforeCommit(object activeObject)
        {
            // set the extended attribute "CarBrand" to the user's selected car brand
            User user = activeObject as User;
            if (user != null)
                Roles.AddUserToRole(user.Username, this.RolesList.SelectedValue);

            // because these changes were made in ApplyChangesBeforeCommit, the host form will commit the changes
        }

        #endregion

    }
}
